﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using Models.Sys;
using Zo.Extensions;
using Zo.Models;

namespace Logics.Sys
{
    public class AdminLogic:BaseLogic
    {
        
        public AdminLogic()
        {
            
        }
        /// <summary>
        /// 获取全部管理员
        /// </summary>
        /// <returns></returns>
        public List<Sys_Admin> GetAllAdmins()
        {
            var list = db.Sys_Admin.ToList();
            return list;
        }

       /// <summary>
       /// 获取单个管理员信息
       /// </summary>
       /// <param name="adminId"></param>
       /// <returns></returns>
        public Sys_Admin GetAdminInfoById(int adminId)
        {
            var info = db.Sys_Admin.Where(c => c.Id == adminId).FirstOrDefault();
            if (info==null)
            {
                throw new ErrorBox("Admin does not exist!");
            }
            return info;
        }

        /// <summary>
        /// 保存管理员信息
        /// </summary>
        /// <param name="info"></param>
        /// <param name="roles"></param>
        /// <returns></returns>
        public bool SaveInfo(Sys_Admin info,int[] roles)
        {
           
            if (info.Id > 0)
            {
                var admin = db.Sys_Admin.Where(c => c.Id.Equals(info.Id)).FirstOrDefault();
                if (admin == null)
                {
                    throw new ErrorBox("Admin does not exist!");
                }
            }
            else
            {
                var admin = db.Sys_Admin.Where(c => c.Name.Trim().ToLower().Equals(info.Name.Trim().ToLower())).FirstOrDefault();
                if(admin!=null)
                {
                    throw new ErrorBox("This admin's name  already exists!");
                }

            }
            if (roles == null || roles.Count() == 0)
            {
                throw new ErrorBox("You must choose  role!");
            }
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    if (info.Id > 0)
                    {
                        var admin = db.Sys_Admin.Where(c => c.Id.Equals(info.Id)).FirstOrDefault();
                        admin.Nickname = info.Nickname.Trim(); ;
                        admin.Email = info.Email;
                        db.SaveChanges();
                    }
                    else
                    {
                        info.Name = info.Name.Trim();
                        db.Sys_Admin.Add(info);
                        db.SaveChanges();
                    }

                    if (info.Id > 0)
                    {
                        string sql = "DELETE FROM " + table_prx + "Sys_AdminRole Where AdminId = " + info.Id;
                        db.Database.ExecuteSqlCommand(sql);
                        List<Sys_AdminRole> list = new List<Sys_AdminRole>();
                        foreach (var ro in roles)
                        {
                            Sys_AdminRole ar = new Sys_AdminRole();
                            ar.AdminId = info.Id;
                            ar.RoleId = ro;
                            ar.CreateTime = DateTime.UtcNow.GetTimeStamp();
                            list.Add(ar);
                        }
                        db.Set<Sys_AdminRole>().AddRange(list);
                        db.SaveChanges();
                    }

                    tran.Commit();
                    return true;
                }
                catch (Exception e)
                {
                    tran.Rollback();
                    throw new ErrorBox(e.Message);
                }

            }         
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public bool Delete(int adminId)
        {
            var admin = db.Sys_Admin.Where(c => c.Id.Equals(adminId)).FirstOrDefault();
            if(admin==null)
            {
                throw new ErrorBox("Admin is not exist");
            }
            if (adminId == 1)
            {
                throw new ErrorBox("Super Admin cannot be deleted");
            }
            using (var tran=db.Database.BeginTransaction())
            {
                try
                {
                    db.Sys_Admin.Remove(admin);
                    db.Database.ExecuteSqlCommand("DELETE FROM " + table_prx + "Sys_AdminRole WHERE AdminId=" + adminId);
                    var rr=db.SaveChanges();
                    tran.Commit();
                    return rr>0;
                }
                catch (Exception e)
                {
                    tran.Rollback();
                    throw e;
                }
                
            }
        }

        /// <summary>
        ///  重置密码
        /// </summary>
        /// <param name="password1"></param>
        /// <param name="password2"></param>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public bool resetPassword(string password1,string password2,int adminId)
        {
            if (string.IsNullOrEmpty(password1)|| string.IsNullOrEmpty(password2))
            {
                throw new ErrorBox("Please Enter Password");
            }
            if (!password1.Equals(password2))
            {
                throw new ErrorBox("The passwords entered twice are inconsistent");
            }
            var admin=db.Sys_Admin.Where(c => c.Id.Equals(adminId)).FirstOrDefault();
            admin.Password = password1;
            return db.SaveChanges()>0;
        }
    }
}
